package com.karry.yl.web.services;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.karry.commons.base.SuperController;
import com.karry.commons.vo.JsonResponse;
import com.karry.yl.domain.elder.CheckInRecords;
import com.karry.yl.domain.elder.Elderly;
import com.karry.yl.domain.healthdata.HealthData;
import com.karry.yl.domain.personnel.Department;
import com.karry.yl.domain.services.Items;
import com.karry.yl.domain.services.Records;
import com.karry.yl.service.elder.CheckInRecordsService;
import com.karry.yl.service.elder.ElderlyService;
import com.karry.yl.service.personnel.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.*;

/**
 * 老人分配
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/elderlyAllocation")
public class ElderlyAllocationController extends SuperController {

    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private ElderlyService elderlyService;
    @Autowired
    private CheckInRecordsService checkInRecordsService;

    @RequestMapping
    public String elderLyAllocationUI(ModelMap map, Integer healthCondition) {
        //查询出本机构下的所有护理部
        List<Department> departments = departmentService.selectList(new EntityWrapper<Department>().eq("isNursingDepartment", true).eq("orgId", currentUser.getOrgId()).eq("deleted", false).orderBy("createdTime", false));
        for (Department department : departments) {
            List<Elderly> elderlies = elderlyService.selectList(new EntityWrapper<Elderly>().eq("nursingDepartmentId", department.getId()).eq("allocationStart", true).eq("orgId", currentUser.getOrgId()).eq("checkedIn", true));
            findCheckInMessage(elderlies);
            department.setElderlyList(elderlies);
        }

        //查询出当前机构中没有入住的老人
        List<Elderly> noCheckedInElderly;
        if (healthCondition != null && healthCondition != 0) {
            noCheckedInElderly = elderlyService.selectList(new EntityWrapper<Elderly>().eq("healthCondition", healthCondition).eq("orgId", currentUser.getOrgId()).eq("allocationStart", false).eq("checkedIn", true));
        } else {
            noCheckedInElderly = elderlyService.selectList(new EntityWrapper<Elderly>().eq("orgId", currentUser.getOrgId()).eq("allocationStart", false).eq("checkedIn", true).orderBy("enterDate"));
        }
        findCheckInMessage(noCheckedInElderly);
        map.put("departments", departments);
        map.put("noCheckedInElderly", noCheckedInElderly);
        return "services/elderlyallocation/allocation";
    }


    /**
     * 查询老人入住的楼号，房间号，床位号
     *
     * @param elderlies
     */
    private void findCheckInMessage(List<Elderly> elderlies) {
        if (elderlies != null && elderlies.size() > 0) {
            for (Elderly elderly : elderlies) {
                CheckInRecords checkInRecords = checkInRecordsService.selectOne(new EntityWrapper<CheckInRecords>().eq("elderlyId", elderly.getId()).eq("orgId", currentUser.getOrgId()).eq("deleted", false));
                //楼号
                elderly.setBuildingNo(checkInRecords.getBuildingNo());
                //房间号
                elderly.setRoomNo(checkInRecords.getRoomNo());
                //床位号
                elderly.setBedNo(checkInRecords.getBedNo());
                //床位Id
                elderly.setBedId(checkInRecords.getBedId());
            }
        }
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public JsonResponse save(String alloactionData) {

        List<Elderly> elderlies = elderlyService.selectList(new EntityWrapper<Elderly>().eq("allocationStart", true).eq("orgId", currentUser.getOrgId()).eq("checkedIn", true).eq("deleted", false));
        if (elderlies != null && elderlies.size() > 0) {
            for (Elderly elderly : elderlies) {
                elderly.setNursingDepartmentId(-1L);
                elderly.setAllocationStart(false);
                elderlyService.updateById(elderly);
            }
        }
        if (!"".equals(alloactionData) && alloactionData != null) {
            final ObjectMapper mapper = new ObjectMapper();
            String dh = ",";
            if (alloactionData.contains(dh)) {
                String[] strings = alloactionData.split(",");
                for (String string : strings) {
                    if (updataAllocation(mapper, string)) {
                        return new JsonResponse(JsonResponse.CODE_FAIL, "失败");
                    }
                }
            } else {
                if (updataAllocation(mapper, alloactionData)) {
                    return new JsonResponse(JsonResponse.CODE_FAIL, "失败");
                }
            }
        }


        return new JsonResponse(JsonResponse.CODE_SUCCESS, "成功");
    }

    /**
     * 跟新分配状态
     * @param mapper
     * @param string
     * @return
     */
    private boolean updataAllocation(ObjectMapper mapper, String string) {
        try {
            Map<String, Long> map = mapper.readValue(string, Map.class);
            Set<String> longs = map.keySet();
            for (String d : longs) {
                Elderly elderly = elderlyService.selectById(map.get(d));
                elderly.setNursingDepartmentId(Long.parseLong(d));
                elderly.setAllocationStart(true);
                elderlyService.updateById(elderly);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return true;
        }
        return false;
    }

}
